package com.example.service.impl;


import com.example.pojo.Position;
import com.example.service.PositionService;
import com.example.utils.SolrUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author BeauFang
 * Date: 2020/9/22
 */
@Service
public class PositionServiceImpl implements PositionService {
    @Autowired
    SolrClient solrClient;

    @Override
    public List<Position> queryPositions(String query) throws IOException, SolrServerException {
        // 第一次查询
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.set("df", "positionName");
        solrQuery.setQuery(query);
        QueryResponse rep1 = solrClient.query(solrQuery);
        SolrDocumentList documents1 = rep1.getResults();
        long count = documents1.getNumFound();
        System.out.println("查询到的职位数量" + count);
        List<Position> list = new ArrayList<>();
        for(SolrDocument d : documents1) {
            list.add(SolrUtils.solrDocument2Bean(d, Position.class));
        }
        // 第二次查询
        SolrDocumentList documents2;
        if (count < 5) {
            SolrQuery solrQuery1 = new SolrQuery();
            solrQuery1.set("q", "positionAdvantage:美女多||员工福利好");
            QueryResponse rep2 = solrClient.query(solrQuery1);
            documents2 = rep2.getResults();
            System.out.println("补充查询到职位数量为" + documents2.getNumFound());
            for(SolrDocument d : documents2) {
                Position position = SolrUtils.solrDocument2Bean(d, Position.class);
                if (list.size() > 5) {
                    break;
                }
                if (!list.contains(position)) {
                    list.add(position);
                }
            }
        }
        return list;
    }
}
